/* Copyright (c) 2009 Maksudul Alam (maksud.buet@gmail.com)
* Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* Thanks to: Remy Sharp for nice JQuery Tutorials
*/
(function($) {
    $.fn.maxgallery = function(options) {

        var galleryOptions = {
            autoSelectFirst: false,
            useCaption: false,
            captionElement: null,
            fullImage: null,
            scrollOverFullImage: true,
            scrollOverThumbs: true,
            width: 700,
            offset: 100,
            scroll: 25,
            regexRule: /(.+?)_resize\.(.+)/g,
            regexReplacement: "$1.$2"
        };
        galleryOptions = $.extend(galleryOptions, options);
        galleryOptions.width = (galleryOptions.width / 2 - 10) | 0;

        //Global Elements
        var _thumbDiv = this;
        var _captionDiv = $(galleryOptions.captionElement);
        var _fullimageDiv = $(galleryOptions.fullImage);
        var _thumbUL = $('ul', _thumbDiv);

        //select first element
        var _selectedThumb = $('li:first', _thumbUL);
        if (galleryOptions.autoSelectFirst) {
            _selectedThumb.addClass("maxgallery_active");
        }

        //var _lastThumbWidth = $('li:last', _thumbUL).width();
        var itemsWidth = _thumbUL.innerWidth() - _thumbDiv.outerWidth();
        var leftOffset = 0;
        var enableScrolling = true;

        if (_thumbUL.width() < galleryOptions.width) {

            enableScrolling = false;

            leftOffset = (galleryOptions.width * 2 + 10 - _thumbUL.width()) / 2;
            _thumbUL.animate({
                'left': leftOffset
            }, 0);

        }

        //Mouse Over Effect...
        $("li img", _thumbUL).each(function(i, item) {
            var thumb = $(item);    //<img> Image
            // fetch the thumbnail _thumbDiv
            var _li = thumb.parents('li'); //<li> TAG
            // if thumbnail is active, fade all the way.
            var _fadeTo = _li.is('.maxgallery_active') ? '1' : '0.3';
            thumb.css({
                display: 'none',
                opacity: _fadeTo
            }).fadeIn(1500);

            thumb.hover
            (
                function() {
                    thumb.fadeTo('fast', 1);
                },
                function() {
                    // don't fade out if the parent is active
                    _li.not('.maxgallery_active').children('img').fadeTo('fast', 0.3);
                }
            );
        });


        function ajaxImageLoad(src) {
            var img = new Image();
            $(_fullimageDiv).addClass('maxgallery_loadingSpinner');

            $(img).load(function() {
                $(this).hide();

                $(_fullimageDiv).removeClass('maxgallery_loadingSpinner');
                $("img", _fullimageDiv).replaceWith(this);
                $(this).attr("id", "photo");

                $(this).css('display', 'none').fadeIn(1000);
                $(this).css("display", "inline");
            })
            .error(function() {
                alert("Image Can't be loaded");
            }).attr('src', src);
        }

        function li_move(offset) {

            if (enableScrolling) {
                leftOffset = leftOffset + offset;
                if (leftOffset >= itemsWidth) {
                    leftOffset = itemsWidth;
                }
                else if (leftOffset < 0)
                    leftOffset = 0;

                _thumbUL.animate({
                    'left': leftOffset * -1
                }, 0);
            }

            return false;
        }

        function li_click(_li_this) {
            if ($(_li_this).is(".maxgallery_active") || $(_li_this).length == 0)
                return false;

            var img = $("img", _li_this);

            var result = img.attr("src").replace(galleryOptions.regexRule, galleryOptions.regexReplacement);
            ajaxImageLoad(result);

            var _liSelThumb = $(_selectedThumb);
            _liSelThumb.removeClass("maxgallery_active");
            _liSelThumb.children('img').fadeTo('fast', 0.3);

            _selectedThumb = _li_this;
            _liSelThumb = $(_li_this);
            _liSelThumb.addClass('maxgallery_active');
            _liSelThumb.children('img').fadeTo('fast', 1);


            _captionDiv.text(img.attr("title"));
            //$("#caption").text(img.attr("title"));

            if (enableScrolling) {
                var x = _liSelThumb.position().left + _liSelThumb.width() / 2;
                var diffScroll = 0;
                if (x > leftOffset + galleryOptions.width + galleryOptions.offset) {
                    diffScroll = x - leftOffset - galleryOptions.width;
                    if (leftOffset + diffScroll > itemsWidth) {
                        diffScroll = itemsWidth - leftOffset;
                    }
                    leftOffset = leftOffset + diffScroll;
                    _thumbUL.animate({
                        'left': leftOffset * -1
                    }, 500);
                }
                else if (x < leftOffset + galleryOptions.width - galleryOptions.offset) {
                    diffScroll = x - leftOffset - galleryOptions.width;
                    if (leftOffset + diffScroll < 0) {
                        diffScroll = -leftOffset;
                    }
                    leftOffset = leftOffset + diffScroll;
                    _thumbUL.animate({
                        'left': leftOffset * -1
                    }, 500);
                }
            }
            return false;
        }

        $("ul li", _thumbDiv).click(function(e) {
            li_click(this);
        });


        //Mouse Scroll for Full Image
        if (galleryOptions.scrollOverFullImage) {
            $(_fullimageDiv).mousewheel(function(event, delta) {
                if (delta > 0)
                    $img = $(_selectedThumb).prev();
                else if (delta < 0)
                    $img = $(_selectedThumb).next();
                else
                    return false;
                if ($img.length >= 0)
                    li_click($img);
                return false;
            });
        }
        //Mouse Scroll for Thumbnails
        if (galleryOptions.scrollOverThumbs) {
            $(_thumbDiv).mousewheel(function(event, delta) {
                if (delta > 0)
                    li_move(-galleryOptions.scroll);
                else if (delta < 0)
                    li_move(galleryOptions.scroll);
                else
                    return false;
            });
        }
    }
})(jQuery);
